package com.aiyige.page.coupon;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ApiUrls;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.Page;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.coupon.adapter.DrawCouponAdapter;
import com.aiyige.page.coupon.model.Coupon;
import com.aiyige.page.coupon.model.DrawCouponImmediatelyRequest;
import com.aiyige.page.coupon.model.UserCoupon;
import com.aiyige.page.coupon.util.CouponUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.netease.nim.uikit.common.activity.UI;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

@Route(path = ARouterConfig.DrawCouponPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class DrawCouponPage extends AppCompatActivity implements CommonDataView.RetrofitStub {

    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.cdv)
    CommonDataView cdv;
    DrawCouponAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_draw_coupon);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        cdv.getRecyclerView().setItemAnimator(null);
        cdv.getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(UIHelper.dip2px(15), UIHelper.dip2px(15), UIHelper.dip2px(15), 0);
            }
        });
        titleTv.setText(R.string.draw_coupon_center);
        adapter = new DrawCouponAdapter();
        cdv.config(adapter, this);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.actionBtn:
                        doDrawCoupon(position);
                        break;
                }
            }
        });
        cdv.doRefreshRequest();
    }

    private void doDrawCoupon(int position) {
        Coupon coupon = adapter.getItem(position);
        if (coupon == null) return;
        new DrawCouponTask(this, position).execute();
    }

    public class DrawCouponTask extends SafeAsyncTask<Object, Object, Object> {
        int position;
        UserCoupon respUserCoupon;
        Coupon sourceCoupon;

        public DrawCouponTask(Activity activity, int position) {
            super(activity, R.string.loading);
            this.position = position;
            sourceCoupon = adapter.getItem(position);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            try {
                if (o instanceof DrawCouponException) {
                    DrawCouponException dce = (DrawCouponException) o;
                    ToastX.show(dce.getErrorMessage());
                    sourceCoupon = adapter.getItem(position);
                    if (sourceCoupon.getStatus().equals(CouponUtil.COUPON_STATUS_NOT_RECEIVE) || sourceCoupon.getStatus().equals(CouponUtil.COUPON_STATUS_RECEIVABLE)) {
                        switch (dce.getErrorCode()) {
                            case ResponseCode.COUPON_LOOT_OUT:
                                sourceCoupon.setStatus(CouponUtil.COUPON_STATUS_NONE);
                                break;
                            case ResponseCode.COUPON_RECEIVED:
                                sourceCoupon.setStatus(CouponUtil.COUPON_STATUS_RECEIVED);
                                break;
                        }
                        adapter.setData(position, sourceCoupon);
                    }
                } else if (o instanceof Exception) {
                    ToastX.show((Exception) o);
                } else {
                    ToastX.show(R.string.draw_coupon_success);
                    sourceCoupon = adapter.getItem(position);
                    if (sourceCoupon.getId().equals(respUserCoupon.getCouponId())) {
                        sourceCoupon.setStatus(respUserCoupon.getReceivedStatus());
                        adapter.setData(position, sourceCoupon);
                    }
                }
            } catch (Exception e) {

            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .drawCouponImmediately(DrawCouponImmediatelyRequest.newBuilder()
                                .couponId(sourceCoupon.getId())
                                .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    ErrorResponse errorResponse = ErrorUtil.handleErrorResponse(response);
                    throw new DrawCouponException(errorResponse.getCode(), errorResponse.getMessage());
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                respUserCoupon = JSON.parseObject(json, UserCoupon.class);
                if (TextUtils.isEmpty(respUserCoupon.getCouponId()) || TextUtils.isEmpty(respUserCoupon.getStatus())) {
                    throw new Exception(StringUtils.getString(R.string.unknown_error));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    @OnClick({R.id.titleBackBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
        }
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().drawCouponCenterList(currentPage, 20);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Coupon> couponList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                couponList.addAll(JSON.parseArray(page.getContent(), Coupon.class));
            }
            for (Coupon item : couponList) {
                if (item == null) continue;
                Coupon safeItem = new Coupon(item);
                resultList.add(safeItem);
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }
}
